package com.smartstate.ems.quartz;

import com.alibaba.fastjson.JSONArray;
import com.smartstate.ems.dto.EquipmentDTO;
import com.smartstate.ems.mapper.EquipmentConfigMapper;
import com.smartstate.ems.mapper.PowerEquipmentEntityDao;
import com.smartstate.ems.vo.AlarmVO;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;


@Slf4j
@Component("mysqlJob")
@RestController
public class PowerEquipmentJob {

    @Resource
    private PowerEquipmentEntityDao powerEquipmentEntityDao;

    @Resource
    private EquipmentConfigMapper equipmentConfigMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisTemplate redisTemplate;

    //上一次有电功能 初始化位0
    private float lastActiveEnergy = 20;

    //上一次无电功能
    private float lastReactiveEnergy = 20;

    //上一次视在能量
    private float lastApparentEnergy = 20;

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 读数据判断是否报警
     *
     * @param
     */
    @GetMapping("/findAll")
    public ArrayList<AlarmVO> equipmentTags() {
        ArrayList<AlarmVO> alarmVOS = new ArrayList<>();
        //TODO 根据设备类型来查 参数可以传设备类型
        List<String> idsByType = findIdsByType(1);
        for (String deviceId : idsByType) {
            //Redis中设备的属性和值
            Map entries = redisTemplate.opsForHash().entries(deviceId);
            if (entries.size() > 0) {
                //根据设备id查询设备属性JSON 转位对象集合
                String tags = findEquipment(deviceId);
                List<EquipmentDTO.AddressData> addressDataList = JSONArray.parseArray(tags, EquipmentDTO.AddressData.class);
                for (EquipmentDTO.AddressData addressData : addressDataList) {
                    //根据属性名获取上下限
                    String attributeName = addressData.getAttributeName();
//                    String down1 = addressData.getDown();
//                    if (!down1.isEmpty()){
//                        float down = Float.parseFloat(down1);
//                    }
//                    float up = Float.parseFloat(addressData.getUp());
                    if ((addressData.getIsAlarm() != null) &&(Integer.parseInt(addressData.getIsAlarm()) == 1) && (((addressData.getDown()!=null && !"".equals(addressData.getDown()))) || (addressData.getUp()!=null && !"".equals( addressData.getUp())))) {
                        AlarmVO alarmVO = new AlarmVO();
                        alarmVO.setDeviceId(deviceId);  //设备id
                        alarmVO.setAttributeName(attributeName); //属性名
                        alarmVO.setAttributeAlias(addressData.getAttributeAlias());  //属性中文名
                        alarmVO.setCycle(addressData.getCycle());  //采集周期
                        alarmVO.setDown(addressData.getDown()); //下限
                        alarmVO.setUp(addressData.getUp()); //上限
                        alarmVO.setDeviation(addressData.getDeviation());//偏差
                        if (entries.get(attributeName) != null) {
                            float parseFloat = Float.parseFloat(entries.get(addressData.getAttributeName()).toString()); //当前值
                            //计算偏差后的值
                            if (addressData.getDeviation() != null && !"".equals(addressData.getDeviation())) {
                                float deviation = Float.parseFloat(addressData.getDeviation());
                                BigDecimal deviationDecimal = new BigDecimal(deviation);
                                BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                parseFloat = nowBigDecimal.add(deviationDecimal).floatValue();
                            }
                            alarmVO.setNow(parseFloat); //处理后的值
                        } else {
                            //没有推送当前值 又设置了是否报警
                            alarmVO.setNow(Float.parseFloat("0")); //当前值
                        }
                        if (entries.get("type") != null){
                            alarmVO.setType(entries.get("type").toString());
                        }
                        alarmVO.setIsAlarm(addressData.getIsAlarm());//是否报警
                        alarmVOS.add(alarmVO);
                    }
                }
            }

        }
        return alarmVOS;
    }


    /**
     * 根据设备id查找设备属性
     *
     * @param deviceId
     * @return
     */
    private String findEquipment(String deviceId) {
        String tags = equipmentConfigMapper.selectTages(deviceId);
        return tags;
    }

    /**
     * 根据设备id在Redis中查询某个设备的属性和属性值
     */
    private Set<Object> findRedisById(String deviceId) {
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(deviceId);
        Set<Object> keySet = entries.keySet();
        return keySet;
    }

    /**
     * 根据设备类型查询该类型的所有设备Id
     *
     * @param deviceType
     * @return
     */
    public List<String> findIdsByType(Integer deviceType) {
        return equipmentConfigMapper.findIdsByType(deviceType);

    }
}
